import backtrader as bt
import psycopg2.extras
import logging
from pyLibs import units, TdxSource, BacktraderUtits as btu
import CStrategy

logging.basicConfig(format="%(asctime)s %(filename)s(line:%(lineno)d) [%(levelname)s] : %(message)s", datefmt="%Y-%M-%d %H:%M:%S", level=logging.DEBUG)


class TestStrategy(btu.BaseStrategy):
    def __init__(self):
        self.datasLength = len(self.getdatanames())

    def next(self):
        stock_15m = self.datas[0]
        stock_60m = self.datas[1]
        print(stock_15m.datetime.datetime(0), stock_15m._name, stock_15m._timeframe, stock_15m._compression,
              stock_15m.open[0], stock_15m.high[0], stock_15m.low[0], stock_15m.close[0])
        print(stock_60m.datetime.datetime(-1), stock_60m._name, stock_60m._timeframe, stock_60m._compression,
              stock_60m.open[-1], stock_60m.high[-1], stock_60m.low[-1], stock_60m.close[-1])





if __name__ == '__main__':
    setting = units.XML2ObjFromFile('./setting.xml').setting
    tdx = TdxSource.Security()
    cerebro = bt.Cerebro()
    #cerebro.addstrategy(CStrategy.BollingerVolatilityBreakout.BollingerVolatilityBreakout)  # 增加一个策略
    cerebro.addstrategy(CStrategy.PinBar.PinBar)
    cerebro.addanalyzer(btu.TradeListAnalyzer, _name='trade_list')
    cerebro.broker.setcash(100000.0)
    cerebro.broker.set_slippage_fixed(fixed=0.001)  # 设置固定滑点
    cerebro.broker.setcommission(commission=0.0003)
    cerebro.broker.addcommissioninfo(btu.StockCommissionScheme())
    conn = units.dbConnect(setting.pgsql)
    try:
        cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
        cursor.execute("SELECT * FROM trading.owner_stock_view WHERE stock_code = '000651'")
        row = cursor.fetchone()
    except Exception as e:
        print('str(Exception):\t', str(Exception))
        print('str(e):\t\t', str(e))
        print('repr(e):\t', repr(e))
        #print('e.message:\t', e.message)
        #print('traceback.print_exc():', aceback.print_exc())
        #print('traceback.format_exc():\n%s' % traceback.format_exc())
    finally:
        units.dbDisconnect(conn)
    data_15m = btu.StockPandasData(dataname=tdx.get_stock_data(row, '1D').data,
                                   timeframe=bt.TimeFrame.Days,
                                   compression=1)
    '''data_60m = btu.StockPandasData(dataname=tdx.get_stock_data(row, '60M').data,
                                   timeframe=bt.TimeFrame.Minutes,
                                   compression=60)'''
    cerebro.adddata(data_15m, name=row['tdx_code'] + '_1D')
    # cerebro.adddata(data_60m, name=row['tdx_code'] + '_60T')
    start_value = cerebro.broker.getvalue()
    print('Starting Portfolio Value: %.2f' % start_value)
    result = cerebro.run(tradehistory=True)
    final_value = cerebro.broker.getvalue()
    print('Final Portfolio Value: \033[36m %.2f \033[0m' % final_value)
    print('\033[31m Net Profit: %.2f%% \033[0m' % ((final_value - start_value) / start_value * 100))
    for index, key in enumerate(result[0].watch):
        print(index, key)
        print(result[0].watch[key])
    trade_list, treade_dict = result[0].analyzers.trade_list.get_analysis()
    print('交易订单列表：')
    print(trade_list)
    print('交易对应的买卖点：')
    print(treade_dict)
    # cerebro.plot()